﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SMARTMobile.WinPhone.Helpers
{
    public static class DataRowToObjectHelper
    {
        public static void ConvertTo(object obj, string fieldName, object fieldValue)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (propertyInfo == null)
            {
                return;
            }

            if (fieldValue == DBNull.Value)
            {
                fieldValue = null;
                ////if (propertyInfo.PropertyType == typeof(bool?))
                ////{
                ////    Type underlyingType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
                ////    propertyInfo.SetValue(obj, Convert.ChangeType(fieldValue, propertyInfo.PropertyType), null);
                ////    return;
                ////}
            }

            Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;

            object safeValue = new object();
            
            if (t.FullName == "System.String")
            {
                safeValue = (string.IsNullOrEmpty(fieldValue.ToString())) ? null : Convert.ChangeType(fieldValue, t);
            }
            else if (t.FullName == "System.Double")
            {
                safeValue = (string.IsNullOrEmpty(fieldValue.ToString())) ? 0 : Convert.ChangeType(fieldValue, t);
            }
            else
            {
                safeValue = (fieldValue == null) ? null : Convert.ChangeType(fieldValue, t);
            }

            propertyInfo.SetValue(obj, safeValue, null);
        }

        public static string GetValueFromPropertyName(object obj, string fieldName)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (propertyInfo == null)
            {
                return string.Empty;
            }

            var propertyValue = propertyInfo.GetValue(obj, null);
            if (propertyValue == null)
            {
                return string.Empty;
            }
            else
            {
                return propertyValue.ToString();
            }
        }


    }
}
